package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Wrapper;

@RestController
@RequestMapping("/user")
//碰到user
public class UserController {
    @Resource
    UserMapper userMapper;

    @PostMapping
    public Result<?> save(@RequestBody User user){
        userMapper.insert(user);
        return Result.success();
    }
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user){
        LambdaQueryWrapper<User>wrapper=new LambdaQueryWrapper<User>();
        wrapper.eq(User::getUsername,user.getUsername()).eq(User::getPassword,user.getPassword());
        User res=userMapper.selectOne(wrapper);
        if(res==null){
            return Result.error("-1","用户名或者密码错误");
        }
        return Result.success();
    }
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user){
        LambdaQueryWrapper<User>wrapper=new LambdaQueryWrapper<User>();
        wrapper.eq(User::getUsername,user.getUsername());
        User res=userMapper.selectOne(wrapper);
        if(res!=null){
            return Result.error("-1","用户名已经存在");
        }
        if(user.getPassword()==null){
            user.setPassword("123456");
        }
        userMapper.insert(user);
        return Result.success();
    }
    @PutMapping
    public Result<?> update(@RequestBody User user){
        userMapper.updateById(user);
        return Result.success();
    }
    @GetMapping
    public Result<?> findPage(@RequestParam Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        LambdaQueryWrapper<User>wrapper= Wrappers.<User>lambdaQuery();
        if(StrUtil.isNotBlank(search)){
            wrapper.like(User::getUsername,search);
        }
        Page<User> userPage=userMapper.selectPage(new Page<>(pageNum,pageSize), wrapper);
        return Result.success(userPage);
    }
    @GetMapping("/username=")
    public User selectOne(@RequestParam String search){
        LambdaQueryWrapper<User>wrapper= Wrappers.<User>lambdaQuery();
        if(StrUtil.isNotBlank(search)){
            wrapper.like(User::getUsername,search);
        }
        return userMapper.selectOne(wrapper);
    }
    @GetMapping("/{id}")
    public Result<?> selectById(@PathVariable Long id){
        return Result.success(userMapper.selectById(id));
    }
    @DeleteMapping("/{id}")
    public Result<?> update (@PathVariable Long id){
        userMapper.deleteById(id);
        return Result.success();
    }
}
